/*global Ext: true, console: true, window: true*/
Ext.define('notepad.controller.BaseController', {
    extend: 'Ext.app.Controller',
    init: function () {
        "use strict";
        var myApp = this;
        myApp.control({
            'viewport': {
                boxready: function (viewport, width, height, eOpts) {
                    myApp.viewport = viewport;
                }
            },
            'viewport > treepanel': {
                boxready: function (treepanel, width, height, eOpts) {
                    myApp.treePanel = treepanel;
                },
                selectionchange: function (treepanel, selected, eOpts) {
                    //console.log(treepanel, selected, eOpts);
                },
                celldblclick: function (treepanel, td, cellIndex, record, tr, rowIndex, e, eOpts) {
                    var type, tabId, tabFinded = false;

                    function tabResize(tab, width, height, oldWidth, oldHeight, eOpts) {
                        var wrapper = Ext.get(tab.codeWrapperId);
                        if (wrapper.child('.CodeMirror')) {
                            wrapper.child('.CodeMirror').setHeight(height);
                        } else {
                            wrapper.setHeight(height);
                        }
                    }

                    function tabBeforeClose(tab, eOpts) {
                        var curr_hex = window.hex_sha512(tab.codeMirror.getValue());
                        if (curr_hex !== tab.codeTextHash) {
                            Ext.Msg.show({
                                title: 'Сохранить изменения?',
                                msg: 'Вы хотите закрыть несохраненный файл. Сохранить изменения?',
                                buttons: Ext.Msg.YESNOCANCEL,
                                icon: Ext.Msg.QUESTION,
                                callback: function (button) {
                                    var save;
                                    switch (button) {
                                    case 'yes':
                                        save = Ext.getCmp('tabp').down('[name=save]');
                                        save.fireEvent('click', save, {}, {withOutConfirm: true, saveCallback: function () {tab.close(); }});
                                        break;
                                    case 'no':
                                        tab.codeTextHash = curr_hex;
                                        tab.close();
                                        break;
                                    default:
                                    }
                                }
                            });
                            return false;
                        }
                        return true;
                    }

                    function tabActivate(tab, eOpts) {
                        if (tab.codeText) {
                            myApp.fileToolbar.items.each(
                                function (elem, pos, count) {elem.enable(); }
                            );
                        } else {
                            myApp.fileToolbar.items.each(
                                function (elem, pos, count) {elem.disable(); }
                            );
                        }
                    }

                    function ajaxCallback(response) {
                        var mode = 'htmlmixed';
                        switch (type) {
                        case 'xml':
                            mode = 'xml';
                            break;
                        case 'ini':
                            mode = 'asterisk';
                            break;
                        case 'txt':
                        case 'htm':
                        case 'html':
                            mode = 'htmlmixed';
                            break;
                        case 'js':
                            mode = 'javascript';
                            break;
                        case 'css':
                            mode = 'css';
                            break;
                        case 'less':
                            mode = 'less';
                            break;
                        case 'sass':
                            mode = 'sass';
                            break;
                        case 'php':
                            mode = 'php';
                            break;
                        }
                        myApp.tabPanel.add({
                            title: record.data.text,
                            closable: true,
                            fileId: record.data.id,
                            codeWrapperId: tabId,
                            codeText: response.responseText,
                            codeMode: mode,
                            html: '<div id="' + tabId + '"></div>',
                            listeners: {
                                resize: tabResize,
                                beforeclose: tabBeforeClose,
                                activate: tabActivate
                            }
                        });
                    }

                    // ПОШЕЛ КОД
                    if (record.data.leaf) {
                        tabId = encodeURIComponent(record.data.id);
                        myApp.tabPanel.items.each(function (tab, pos, count) {
                            if (tab && tab.codeWrapperId && tab.codeWrapperId === tabId) {
                                tabFinded = true;
                                myApp.tabPanel.setActiveTab(pos);
                            }
                        });
                        if (!tabFinded) {
                            type = record.data.id.split('.');
                            type = type[type.length - 1].toLowerCase();
                            if (type === 'jpg' || type === 'jpeg' || type === 'ico' || type === 'png' || type === 'gif') {
                                myApp.tabPanel.add({
                                    title: record.data.text,
                                    closable: true,
                                    fileId: record.data.id,
                                    codeWrapperId: tabId,
                                    codeMode: 'javascript',
                                    html: '<div id="' + tabId + '" style="overflow: auto;"><img src="' + record.data.id.substr(record.data.id.indexOf('/')) + '"/></div>',
                                    listeners: {
                                        resize: tabResize,
                                        activate: tabActivate
                                    }
                                });
                            } else {
                                Ext.Ajax.request({
                                    method: 'GET',
                                    url: 'php/file-get.php',
                                    params: {
                                        name: record.data.id
                                    },
                                    success: ajaxCallback
                                });
                            }
                        }
                    }
                }
            },
            'viewport > treepanel > toolbar': {
                boxready: function (toolbar, width, height, eOpts) {
                    myApp.treeToolbar = toolbar;
                }
            },
            'viewport > treepanel > toolbar [name=reload]': {
                boxready: function (btn, width, height, eOpts) {},
                click: function (btn, e, eOpts) {
                    var tree = myApp.treePanel,
                        treeStore = tree.store,
                        nodesToLoad = ['www']/*,
                        expandedNodes = []*/;

                    Ext.each(
                        tree.getView().getNodes(),
                        function (item, index, allNodes) {
                            var rec = tree.getView().getRecord(item);
                            if (rec.isExpanded()) {
                                nodesToLoad.push(rec.getId());
                                //expandedNodes.push({id: rec.getId(), path: rec.getPath()});
                            }
                        }
                    );

                    //tree.getRootNode().removeAll(false);
                    treeStore.load({
                        params: {nodes:JSON.stringify(nodesToLoad)}/*,
                            callback: function(){
                            Ext.each(expandedNodes, function(item){
                                var node = treeStore.getNodeById(item.id);
                                if(node){
                                    tree.expandPath(item.path, undefined, undefined, function(){console.log(arguments);});
                                }
                            })
                        }*/
                    });
                    /*Ext.each(expandedNodes, function (item) {
                        var refreshNode = treeStore.getNodeById(item.id);
                        if (refreshNode) {
                            refreshNode.removeAll(false);
                            treeStore.load({
                                nodes : nodesToLoad
                            });
                        }
                        //tree.expandPath(item.path);
                    });*/

                    /*var refreshNode = treeStore.getNodeById('/web-editor');
                    refreshNode.removeAll(false);
                    treeStore.load({
                        node : refreshNode
                    });*/

                    /*var viewRefresher = function() {
                        view.refresh();
                    };

                    treeStore.load({
                        node: record,
                        callback: viewRefresher
                    });*/

                    /**/
                    //tree.collapseAll();
                    //tree.store.reload();
                }
            },
            'viewport > tabpanel': {
                boxready: function (self, width, height, eOpts) {
                    myApp.tabPanel = self;
                },
                add: function (tabpanel, component, pos, eOpts) {
                    var activeTab = myApp.tabPanel.setActiveTab(pos);
                    if (activeTab.codeText) {
                        // свойства codeText нет у картинок
                        activeTab.codeMirror = window.CodeMirror(
                            window.document.getElementById(activeTab.codeWrapperId),
                            {
                                value: activeTab.codeText,
                                mode: activeTab.codeMode,
                                lineNumbers : true
                            }
                        );
                        // Запоминаем хеш
                        activeTab.codeTextHash = window.hex_sha512(activeTab.codeMirror.getValue());
                    }
                },
                remove: function (tabpanel, component, eOpts) {
                    if (!Ext.getCmp('tabp').items.length) {
                        // дизаблим кнопки
                        myApp.fileToolbar.items.each(
                            function (elem, pos, count) {elem.disable(); }
                        );
                    }
                }
            },
            'viewport > tabpanel > toolbar': {
                boxready: function (toolbar, width, height, eOpts) {
                    myApp.fileToolbar = toolbar;
                }
            },
            'viewport > tabpanel > toolbar [name=save]': {
                boxready: function (btn, width, height, eOpts) {},
                click: function (btn, e, eOpts) {
                    var tab = myApp.tabPanel.getActiveTab(),
                        text = tab.codeMirror.getValue();
                    function save(tab, text, callback) {
                        Ext.Ajax.request({
                            method: 'POST',
                            url: 'php/file-put.php?name=' + encodeURIComponent(tab.fileId),
                            params: {
                                text: text
                            },
                            success: function () {
                                tab.codeTextHash = window.hex_sha512(text);
                                tab.codeText = text;
                                callback && callback();
                            }
                        });
                    }

                    if (btn.isDisabled() || window.hex_sha512(tab.codeMirror.getValue()) === tab.codeTextHash) {
                        return;
                    }

                    if (eOpts.withOutConfirm) {
                        save(tab, text, eOpts.saveCallback);
                    } else {
                        Ext.Msg.confirm('Внимание!', 'Вы действительно хотите сохранить изменения?', function (btn) {if (btn === 'yes') {save(tab, text); } });
                    }
                }
            },
            'viewport > tabpanel > toolbar [name=reload]': {
                boxready: function (btn, width, height, eOpts) {},
                click: function (btn, e, eOpts) {
                    var tab = myApp.tabPanel.getActiveTab(),
                        text = tab.codeMirror.getValue();

                    function reload() {
                        tab.codeMirror.setValue(tab.codeText);
                    }

                    if (btn.isDisabled() || window.hex_sha512(tab.codeMirror.getValue()) === tab.codeTextHash) {
                        return;
                    }

                    Ext.Msg.confirm('Внимание!', 'Вы действительно хотите откатить изменения?', function (btn) {
                        if (btn === 'yes') {
                            reload();
                        }
                    });
                }
            }
        });
    }
});